package com.elm.service.impl;

import com.elm.mapper.FoodMapper;
import com.elm.po.Food;
import com.elm.po.User;
import com.elm.service.FoodService;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {
    @Autowired
    private FoodMapper foodMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    private String getCurrentUserType() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserTypeFromToken(token);
    }

    private String getCurrentUserId() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserIdFromToken(token);
    }

    @Override
    public List<Food> getFoodByBusinessId(Integer businessId) {
        return foodMapper.getFoodByBusinessId(businessId);
    }

    @Override
    public List<Food> getAllReviewingFood() {
        if (!"admin".equals(getCurrentUserType())) {
            throw new RuntimeException("仅管理员可查看待审核食品");
        }
        return foodMapper.getAllReviewingFood();
    }

    @Override
    public int updateReviewingBusinessInfo(Integer foodId, boolean result) {
        if (!"admin".equals(getCurrentUserType())) {
            throw new RuntimeException("仅管理员可审核食品");
        }
        String status = result ? "approved" : "rejected";
        return foodMapper.updateReviewingFoodInfo(foodId, status);
    }

    @Override
    public int updateFoodInfo(Food food) {
        User currentUser = userService.getUserById(getCurrentUserId());
        if (!"boss".equals(currentUser.getUserType()) || 
            !currentUser.getBusinessId().equals(food.getBusinessId())) {
            throw new RuntimeException("仅商家老板可修改食品信息");
        }
        return foodMapper.updateFoodInfo(food);
    }

    @Override
    public int createFood(Food food) {
        User boss = userService.getUserById(getCurrentUserId());
        if (!"boss".equals(boss.getUserType())) {
            throw new RuntimeException("仅商家老板可新增食品");
        }
        food.setBusinessId(boss.getBusinessId());
        return foodMapper.createFood(food);
    }

    @Override
    public int updateFoodStatus(Food food) {
        User staff = userService.getUserById(getCurrentUserId());
        if (!"staff".equals(staff.getUserType()) || 
            !staff.getBusinessId().equals(food.getBusinessId())) {
            throw new RuntimeException("仅本店铺员工可修改食品状态");
        }
        return foodMapper.updateFoodStatus(food);
    }
}